<template>
    <AdminSkeleton>
        <template #header>
            <div class="params-form">
                <el-form :model="workParamsForm" label-width="auto" style="max-width: 600px">
                    <el-form-item label="日期">
                        <el-date-picker
                            v-model="workParamsForm.date"
                            type="date"
                            placeholder="请选择日期"
                            size="small"
                            format="YYYY/MM/DD"
                            value-format="YYYY-MM-DD"
                        />
                    </el-form-item>                         
                    <el-form-item label="状态">
                        <el-select
                            v-model="workParamsForm.status"
                            placeholder="Select"
                            size="small"
                            style="width:100px"
                        >
                        <el-option
                            v-for="item in stausOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                        </el-select>
                    </el-form-item >                        
                    <el-form-item label="描述">
                        <el-input v-model="workParamsForm.desc" placeholder="描述" size="small"/>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" size="small" @click="getUsersInfo(workParamsForm)">查询</el-button>
                    </el-form-item>
                </el-form>
            </div>            
        </template>
        <template #control>
            <el-button type="success" size="small" title="新增" @click="editWorklog('add',{})">
                <el-icon size="18"><DocumentAdd /></el-icon>
            </el-button>
        </template>
        <template #content>
            <el-table :data="worklogTable" style="width: 100%"
                v-loading="tableLoading"
                size="small"
                
            >
                <el-table-column fixed prop="ID" label="ID" width="70" />
                <el-table-column fixed prop="DESCRIPTION" label="描述" width="220" />
                <el-table-column prop="STATUS" label="状态">
                    <template #default="{row}">
                        <div class="status-box" :class="[{fin:row.STATUS === '完成'},{away:row.STATUS === '持续'}]">
                            {{ row.STATUS }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="SCHEDFINISH" label="计划完成时间" width="120">
                    <template #default="{row}">
                        {{ dateFormat(row.SCHEDFINISH) }}
                    </template>
                </el-table-column>
                <el-table-column prop="ACTFINISH" label="实际完成时间" width="120">
                    <template #default="{row}">
                        {{ dateFormat(row.ACTFINISH) }}
                    </template>
                </el-table-column>
                <el-table-column prop="LONG_DESC" label="完成情况" width="220"/>
                <el-table-column prop="REMARK" label="备注" width="220"/>
                <el-table-column prop="B_TYPE" label="大类" />
                <el-table-column prop="S_TYPE" label="小类" />
                <el-table-column prop="JOBID" label="JOBID" />
                <el-table-column prop="SHENGCHENGDATE" label="生成时间" width="120">
                    <template #default="{row}">
                        {{ dateFormat(row.SHENGCHENGDATE) }}
                    </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" min-width="120">
                    <template #default="{row}">
                        <el-button type="primary" size="small" title="编辑" @click="editWorklog('update',row)">
                            <el-icon><Edit /></el-icon>
                        </el-button>
                        <el-button  type="warning" size="small" title="复制" @click="editWorklog('copy',row)">
                            <el-icon><CopyDocument /></el-icon>
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </template>
    </AdminSkeleton>
    <Drawer ref="drawerRef" :title="title" :size="size" 
        @cancel-submit="resetForm"
        @submit="editSubmit(submitType,editForm)"
    >
        <el-form :model="editForm"  
            ref="updateFormRef"
            :rules="rules"
        >
            <el-form-item label="ID" :label-width="formLabelWidth">
                <el-input v-model="editForm.ID" autocomplete="off" disabled/>
            </el-form-item>
            <el-form-item label="描述" :label-width="formLabelWidth" rop="DESCRIPTION">
                <el-input v-model="editForm.DESCRIPTION" autocomplete="off" type="textarea"/>
            </el-form-item>
            <el-form-item label="状态" :label-width="formLabelWidth" prop="STATUS">
                <el-select
                    v-model="editForm.STATUS"
                    placeholder="状态"
                >
                    <el-option v-for="item in stausOptions" :label="item.label" :value="item.value" />
                </el-select>  
            </el-form-item>
            <el-form-item label="计划完成时间" :label-width="formLabelWidth" prop="SCHEDFINISH">
                <el-date-picker
                    v-model="editForm.SCHEDFINISH"
                    type="date"
                    placeholder="请选择日期"
                    format="YYYY/MM/DD"
                    value-format="YYYY-MM-DD"
                />
            </el-form-item>
            <el-form-item label="实际完成时间" :label-width="formLabelWidth" > 
                <el-date-picker
                    v-model="editForm.ACTFINISH"
                    type="date"
                    placeholder="请选择日期"
                    format="YYYY/MM/DD"
                    value-format="YYYY-MM-DD"
                />
            </el-form-item>
            <el-form-item label="完成情况" :label-width="formLabelWidth" > 
                <el-input v-model="editForm.LONG_DESC" autocomplete="off" type="textarea"/>
            </el-form-item>
            <el-form-item label="备注" :label-width="formLabelWidth">
                <el-input v-model="editForm.REMARK" autocomplete="off" type="textarea"/>
            </el-form-item>
            <el-form-item label="大类" :label-width="formLabelWidth" prop="B_TYPE">
                <el-select
                    v-model="editForm.B_TYPE"
                    placeholder="请选择大类"
                    @change="btSelectChange"
                >
                    <el-option v-for="item in workType" :label="item.label" :value="item.label" />
                </el-select>
            </el-form-item>
            <el-form-item label="小类" :label-width="formLabelWidth" prop="S_TYPE">
                <el-select
                    v-model="editForm.S_TYPE"
                    placeholder="请选择小类"                    
                >
                    <el-option v-for="item in sTypeArr" :label="item.label" :value="item.label" />
                </el-select>
            </el-form-item>
            <!-- <el-form-item label="JOBID" :label-width="formLabelWidth"> -->
                <!-- <el-input v-model="editForm.JOBID" autocomplete="off" disabled/> -->
            <!-- </el-form-item> -->
            <!-- <el-form-item label="生成时间" :label-width="formLabelWidth"> -->
                <!-- <el-input v-model="editForm.SHENGCHENGDATE" autocomplete="off" disabled/> -->
            <!-- </el-form-item> -->
      </el-form>
    </Drawer>
</template>

<script setup>
import {ref , reactive} from 'vue'
import AdminSkeleton from '@/components/AdminSkeleton.vue'
import { getWorklogInfo , handleWorklog} from '@/utils/worklogApi/worklog'
import { msgOpen } from '@/utils/msg'
import Drawer from '@/components/Drawer.vue'
import { objCopy } from '@/utils/objCopy'

const now = new Date()
const dateFormat = (date)=>{
    let currentDate
    if(date){
        let newDate = new Date(date)
        let year = newDate.getFullYear()  // 年份
        let month = newDate.getMonth() + 1  // 月份，返回值为0-11，所以需要加1
        let day = newDate.getDate()  // 日期 
        month = month < 10 ? '0' + month : month.toString()// 对月份和日期进行补零
        day = day < 10 ? '0' + day : day.toString()
        currentDate = year + "-" + month + "-" + day
    }else{
        currentDate = ""
    }    
    return currentDate
}

//状态选项
let stausOptions = [
    {label:"",value:""},
    {label:"跟进",value:"跟进"},
    {label:"完成",value:"完成"},
    {label:"持续跟进",value:"持续跟进"},
]

//参数表单对象
let workParamsForm = reactive({
    date:dateFormat(now),
    status:"",
    desc:""
})

//worklog工作表
let worklogTable = ref([])
let tableLoading = ref(false)
let workType = ref([])
let sTypeArr = ref([]) //用于大类选择后，获取相应的小类

//抽屉
let title = ref("")
let size = ref("50%")
let formLabelWidth = ref("120")

//编辑worklog信息
let drawerRef = ref(null) //组件ref
let editForm = reactive({
    ID:'',
    DESCRIPTION:'',
    STATUS:'',
    SCHEDFINISH:'',
    ACTFINISH:'',
    LONG_DESC:'',
    REMARK:'',
    B_TYPE:'',
    S_TYPE:'',
    JOBID:'',
    SHENGCHENGDATE:''
})
let submitType = ref('')

//表单验证ref
let updateFormRef = ref(null)
//输入框验证规则
let rules = reactive({
    DESCRIPTION: [
        { required: true, message: '请输入描述', trigger: 'blur' },
    ],
    STATUS: [
        { required: true, message: '请选择状态', trigger: 'blur' },
    ],
    SCHEDFINISH: [
        { required: true, message: '请选择日期', trigger: 'blur' },
    ],
    B_TYPE: [
        { required: true, message: '请选择大类', trigger: 'blur' },
    ],
    S_TYPE: [
        { required: true, message: '请选择小类', trigger: 'blur' },
    ]
})

/**
 * 大小类转换为树形
 * @param {Array} arr workType 原数组对象 
 */
const bsTypeToTree = (arr)=>{
    // 1. 按 B_TYPE 分组并去重 S_TYPE
    const grouped = arr.reduce((acc, { B_TYPE, S_TYPE }) => {
            if (!acc[B_TYPE]) acc[B_TYPE] = new Set();
        acc[B_TYPE].add(S_TYPE); // Set 自动去重
        return acc;
    }, {});   
    // 2. 转换为树形结构
    const tree = Object.entries(grouped).map(([label, sTypes]) => ({
        label,
        children: Array.from(sTypes).map(sType => ({ label: sType }))
    }))
    return tree
}

/**
 * 获取worklog信息
 * @param {Object} form  //参数表单对象
 */
const getUsersInfo = async (form)=>{
    // console.log(form);
    tableLoading.value = true
    let worklogInfo = await getWorklogInfo(form)
    // console.log(worklogInfo)
    workType.value = bsTypeToTree(worklogInfo.resDatas.workTypeInfo)
    worklogTable.value = worklogInfo.resDatas.worklogInfo
    tableLoading.value = false
    msgOpen(worklogInfo.msg,"success")    
}

//重置表单
const resetForm = ()=>{
    editForm = reactive({
        ID:'',
        DESCRIPTION:'',
        STATUS:'',
        SCHEDFINISH:'',
        ACTFINISH:'',
        LONG_DESC:'',
        REMARK:'',
        B_TYPE:'',
        S_TYPE:'',
        JOBID:'',
        SHENGCHENGDATE:''
    })
}

/**
 * 
 * @param {String} type 处理类型 
 * @param {Object} row 行对象
 */
const editWorklog = (type,row)=>{
    // console.log(type);
    // console.log(row);
    submitType.value = (type === "add" ||  type === "copy") ? "add" : type
    drawerRef.value.open()    
    if(type === 'update') {
        title.value = "编辑"
        editForm = row
        editForm.SCHEDFINISH = dateFormat(row.SCHEDFINISH)
        editForm.ACTFINISH = dateFormat(row.ACTFINISH)
    }
    if(type === 'add' || type === 'copy') {
        title.value = "新增"
        resetForm()
    } 
    if( type === 'copy') {
        editForm = objCopy(row,editForm)
        editForm.ID = ""
        editForm.JOBID = "" 
        editForm.SHENGCHENGDATE = "" 
    }  
}

/**
 * 大类改变时小类来联动改变
 * @param {String} val select选择器选中的值 
 */
const btSelectChange = (val)=>{
    // console.log(val);
    workType.value.filter(item=>{
        if(val === item.label) sTypeArr.value = item.children
    })
}

/**
 * 处理用户方法
 * @param {Object} data 更新用户表单对象
 * @param {String} type 处理类型
 */
const editSubmit = async (type,data)=>{
    // console.log(type);
    // console.log(data);
    let newWorklog = await handleWorklog(type,data)
    // console.log(newWorklog)
    drawerRef.value.hideLoading()
    drawerRef.value.close()
    newWorklog.status ? msgOpen(newWorklog.msg,'success') : msgOpen(newWorklog.msg)
    getUsersInfo(workParamsForm)
    resetForm()
}

</script>

<style lang="less" scoped>
.params-form{
    height: 100%;
    width: 100%;
    .el-form{
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: flex-start;
        .el-form-item{
            margin-bottom: 0;
            margin-right: .3125rem;
        }
    }
    
}

.el-table{
    height: 95%;
    .status-box{
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: .1875rem;
    }
    .status-box.fin{
        background-color: #00e676;
    }
    .status-box.away{
        background-color: #03a9f4;
    }
}

</style>